set(CMAKE_POLICY_DEFAULT_CMP0074 NEW)

cmake_minimum_required(VERSION 3.10)
project(chunkmaster)
set(CMAKE_CXX_STANDARD 17)

# 包含server和disk头文件
include_directories(../../physical_layer/server/include)
include_directories(../../physical_layer/disk/include)

# 链接server和disk动态库
link_directories(../../physical_layer/server/build)
link_directories(../../physical_layer/disk/build)
link_directories(/opt/homebrew/lib)

find_package(nlohmann_json REQUIRED)

# gRPC/Protobuf自动生成

set(GENERATED_SRC_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated)
file(MAKE_DIRECTORY ${GENERATED_SRC_DIR})

find_program(_PROTOBUF_PROTOC protoc)
find_program(_GRPC_CPP_PLUGIN_EXECUTABLE grpc_cpp_plugin)
set(PROTO_SRC chunkmaster.proto)

add_custom_command(
  OUTPUT ${GENERATED_SRC_DIR}/chunkmaster.pb.cc ${GENERATED_SRC_DIR}/chunkmaster.pb.h
  COMMAND ${_PROTOBUF_PROTOC}
  ARGS --cpp_out=${GENERATED_SRC_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR} ${PROTO_SRC}
  DEPENDS ${PROTO_SRC})

add_custom_command(
  OUTPUT ${GENERATED_SRC_DIR}/chunkmaster.grpc.pb.cc ${GENERATED_SRC_DIR}/chunkmaster.grpc.pb.h
  COMMAND ${_PROTOBUF_PROTOC}
  ARGS --grpc_out=${GENERATED_SRC_DIR} --plugin=protoc-gen-grpc=${_GRPC_CPP_PLUGIN_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR} ${PROTO_SRC}
  DEPENDS ${PROTO_SRC})

add_custom_target(proto_gen ALL DEPENDS
  ${GENERATED_SRC_DIR}/chunkmaster.pb.cc
  ${GENERATED_SRC_DIR}/chunkmaster.pb.h
  ${GENERATED_SRC_DIR}/chunkmaster.grpc.pb.cc
  ${GENERATED_SRC_DIR}/chunkmaster.grpc.pb.h
)

add_executable(chunkmaster
  chunkmaster.cpp topo.cpp pool.cpp cli.cpp grpc_server.cpp
  ${GENERATED_SRC_DIR}/chunkmaster.pb.cc
  ${GENERATED_SRC_DIR}/chunkmaster.grpc.pb.cc
)
add_dependencies(chunkmaster proto_gen)

# 用pkg-config获取gRPC/Protobuf编译和链接参数
find_package(PkgConfig REQUIRED)
pkg_check_modules(GRPC REQUIRED grpc++)
pkg_check_modules(PROTOBUF REQUIRED protobuf)

target_include_directories(chunkmaster PRIVATE ${GRPC_INCLUDE_DIRS} ${PROTOBUF_INCLUDE_DIRS} ${GENERATED_SRC_DIR})
target_link_libraries(chunkmaster PRIVATE nlohmann_json::nlohmann_json server_simulator disk_simulator dl readline ${GRPC_LIBRARIES} ${PROTOBUF_LIBRARIES}) 